<html>
	<head>
		<title>Se riesci a leggermi vuol dire che mi stai capendo</title>
		<link href="/css/style.css" rel="stylesheet" type="text/css">
	</head>
	<body>
        <p><h1>{{nome}}</h1></p>
		<div id="editor" autofocus></div>

		<script src="http://ajaxorg.github.com/ace/build/src/ace.js"></script>
		<script src="/channel/bcsocket.js"></script>
		<script src="/share/share.uncompressed.js"></script>
		<script src="/share/ace.js"></script>
		<script>

    		var editor = ace.edit("editor");
    		var documento;

            callback = function() {
                documento.close();
                var f = document.createElement("form");
                    f.method='post';
                    f.action='/delete.html';
                    f.style.visibility="hidden";

                    var i = document.createElement("input"); //input element, text
                    i.type='hidden';
                    i.name='titolo';
                    i.value='{{nome}}'

                    f.appendChild(i);
                    document.body.appendChild(f);
                    f.submit();
                //docx.close();
            };
                //sharejs.disconnect();
    		sharejs.open('{{nome}}', 'text', function(error, doc) {
        		//doc.attach_ace(editor);
        		//doc.insert(0, "cazzo\n");
        		// doc.on('exit', function(op) {
        		// alert(op);
        		// alert('documento cancellato');
        		// this.close();
        		// });
          //       func = "doc.close()";
                //console.warn(client);
                //console.warn(doc);

                // doc.detach_ace;
        		doc.attach_ace(editor);
                editor.focus();
        		//documento=doc;
                // doc.on('shout', function (msg) {
                //     alert(msg);
                //     if (msg == 'CHIUDERE'){
                //         doc.exit(function (){
                //             doc.emit('exit');
                //         });
                //     }
                //     //doc.emit('exit');
                // });
                documento=doc;
                documento.on('shout', function (msg) {
                    //alert(msg);
                    if (msg == 'CHIUDERE'){
                        documento.emit('exit');
                        //alert('sono dentro');
                        /*documento.exit(function (){
                            documento.emit('exit');
                        });*/
                    }
                    //doc.emit('exit');
                });
                //doc.emit('pene', 'ano');
               // _results.push(doc.emit('pene', 'ano'));
                // console.log(doc);
                // op = "delete({{nome}}, callback)";
                // doc.submitOp(op)
        		//cazzo=document.getElementById('delete');
        		//cazzo.setAttribute("onclick", 'cancella()');
        		/*cazzo3=document.getElementById('cazzello');
        		cazzo3.setAttribute("onclick","pippa()");
    			function pippa(){
    				cazzo2.on('change', function(op) {console.log(op);});
    			};
    			function scrivi(){ 
    				cazzo2.insert("Hi there!\n", 0);
    			};*/
    		});

            function cancella() {
                if ((confirm('Cancellare il documento???\nATTENZIONE: i dati saranno "IRRIMEDIABILMENTE" persi.'))) {
                    documento.shout('CHIUDERE');
                    documento.exit(callback);
                    

                   /* documento.on('shout', function(msg){
                        if (msg == 'CHIUDERE') {
                            documento.emit('exit');
                        }
                    });
                    //this.emit('shout', value);
                    documento.emit('shout', 'CHIUDERE');*/
                }
            };

            function leave() {
                documento.close();
                location.href = "/";
            };

            (function(){
                if( window.localStorage ){
                    if( !localStorage.getItem( 'firstLoad' ) ){
                        localStorage[ 'firstLoad' ] = true;
                        window.location.reload();
                    }
                    else
                        localStorage.removeItem( 'firstLoad' );
                }
            })();

            function download() {
                documento.save( function(){
                    //alert('salvo');
                    var f = document.createElement("form");
                    f.method='get';
                    f.action='/export.zip';
                    f.style.visibility="hidden";

                    var i = document.createElement("input"); //input element, text
                    i.type='hidden';
                    i.name='file';
                    i.value='{{nome}}';

                    f.appendChild(i);
                    document.body.appendChild(f);
                    f.submit();
                });
            };

            // function pulisci(){
            //     documento.del(0, documento.getText().length, function() {
            //         documento.insert(0, 'cazzo', function(){
            //             //window.location.reload();
            //             //alert(documento.getText());
            //             editor.getSession().getDocument().setValue(documento.getText());
            //             //editor.getSession().setValue(documento.getText());
            //             //documento.getText();
            //         });
            //     });
            //     //editor.getSession().setValue(documento.getText());
            //     //window.location.reload();
            // };
            // function save() {
            //     var f2 = document.createElement("form");
            //     f2.method='post';
            //     f2.action='/save.html';

            //     var i2 = document.createElement("input"); //input element, text
            //     i2.type='hidden';
            //     i2.name='titolo';
            //     i2.value='{{nome}}'

            //     f2.appendChild(i2);
            //     f2.submit();
                // var xmlhttp;
                // if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
                //     xmlhttp=new XMLHttpRequest();
                // }
                // else{// code for IE6, IE5
                //     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                // }
                // xmlhttp.open("GET","/save.html?titolo={{nome}}",true);
                // xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                // xmlhttp.send();
            

    		// function pippo(){
    		// 	console.debug("callback chiamata coglione");
    		// }
            window.onload = function() {
                var fileInput = document.getElementById('fileInput');
                var fileDisplayArea = document.getElementById('fileDisplayArea');
                fileInput.value='';

                fileInput.addEventListener('change', function(evt) {
                    var file = fileInput.files[0];
                    var textType = /text.*/;

                    if (file.type.match(textType)) {
                        // var reader = new FileReader();

                        // reader.onload = function(e) {
                        //     fileDisplayArea.innerText = reader.result;
                        // }

                        //reader.readAsText(file);
                        var reader = new FileReader();
                        //alert(reader);
                        //alert(file);
                        // Read file into memory as UTF-16      
                        reader.readAsText(file, "UTF-8");

                        function updateProgress(evt) {
                            if (evt.lengthComputable) {
                                // evt.loaded and evt.total are ProgressEvent properties
                                var loaded = (evt.loaded / evt.total);
                                if (loaded < 1) {
                                    // Increase the prog bar length
                                    // style.width = (loaded * 200) + "px";
                                    document.getElementById('fileInput').textContent = "caricato il " + loaded +"%";
                                }
                            }
                        };

                        function loaded(evt) {  
                            // Obtain the read file data
                            //alert('ci sono');    
                            var fileString = evt.target.result;
                            editor.getSession().setValue(fileString);
                            document.getElementById('fileInput').value="";
                            //console.log(documento);
                            //documento.save();
                            editor.focus();
                            // documento.del(0, documento.snapshot.length, function() {

                            //     // documento.insert(0, fileString, function(){
                            //     //     //window.location.reload();
                            //     //     //documento.setText(fileString);
                            //     //     //editor.getSession().getDocument().setValue(documento.snapshot);
                            //     //     //alert(documento.getText());
                            //     //     //editor.getSession().getDocument().setValue(documento.getText());
                            //     //     //editor.getSession().setValue(documento.getText());
                            //     //     //documento.getText();
                            //     // });
                            // });
                            //document.getElementById('fileInput').textContent = fileString;
                        };

                        function errorHandler(evt) {
                            if(evt.target.error.name == "NOT_READABLE_ERR") {
                                document.getElementById('fileInput').textContent = "si è verificato un errore nel caricamento";
                            }
                        };

                        // Handle progress, success, and errors
                        reader.onprogress = updateProgress;
                        reader.onload = loaded;
                        reader.onerror = errorHandler;

                    } 
                    else {
                        fileDisplayArea.innerText = "Il file deve essere .txt";
                    }
                });
            }

            function salva(){
                documento.save(function(){
                    alert('documento salvato');
                });
                //console.log(documento.committedVersion);
            }
		</script>
		<button type="button" id="delete" onclick="cancella()">Cancella Documento</button>
        <!-- <button type="button" id="clean" onclick="pulisci()">Importa Documento</button> -->
        <button type="button" id="leave" onclick="leave()">Chiudi Documento</button>
        <button type="button" id="export" onclick="download()">Esporta Documento</button>
        <button type="button" id="save" onclick="salva()">Salva</button>
        <h1>Importa Documento</h1>
        <div>
            Seleziona un file .txt: 
            <input type="file" id="fileInput">
        </div>
        <pre id="fileDisplayArea"><pre>
        <!-- <form action="/import" method="post" enctype="multipart/form-data">
            <input type="file" name="filename" />
            <input type="submit" value="Upload" />
        </form> -->
        <!-- <button type="button" id="go" onclick="go()">GO!</button> -->
		<!-- <button type="button" id="cazzello">PROVA2</button> -->
		<!-- <form method="post" action="/delete.html">
			Cancella documento <input type="hidden" name="titolo" value="{{nome}}"/>
     		<input type="submit" value="Cancella" />
     	</form> -->
        <!-- <form name="cleaner">
            <input type="hidden" name="titolo" value="{{nome}}"/>    
        </form> -->
	</body>
</html>